using MediatR;
using Traceability.API.APPLications.Commands.ImmunityInfo;
using Traceability.API.Dtos;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.APPLications.CommandHanders.ImmunityInfo
{
    /// <summary>
    /// 添加免疫信息命令处理器
    /// </summary>
    public class AddImmunityInfoCommandHandler : IRequestHandler<AddImmunityInfoCommand, APIResult<ImmunityInfoDto>>
    {
        private readonly MyDbContext _context;

        public AddImmunityInfoCommandHandler(MyDbContext context)
        {
            _context = context;
        }

        public async Task<APIResult<ImmunityInfoDto>> Handle(AddImmunityInfoCommand request, CancellationToken cancellationToken)
        {
            APIResult<ImmunityInfoDto> result = new APIResult<ImmunityInfoDto>();
            
            try
            {
                var immunityInfo = new Domain.ImmunityInfo
                {
                    RearingDays = request.RearingDays,
                    Way = request.Way,
                    Function = request.Function,
                    ProductionBatch = request.ProductionBatch
                };

                _context.ImmunityInfos.Add(immunityInfo);
                await _context.SaveChangesAsync(cancellationToken);

                result.Data = new ImmunityInfoDto
                {
                    ID = immunityInfo.ID,
                    RearingDays = immunityInfo.RearingDays,
                    Way = immunityInfo.Way,
                    Function = immunityInfo.Function,
                    ProductionBatch = immunityInfo.ProductionBatch
                };

                result.Code = APIEnum.添加成功;
                result.Message = "免疫信息添加成功";
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.添加失败;
                result.Message = $"添加免疫信息失败: {ex.Message}";
            }
            
            return result;
        }
    }
} 